package org.microser.gataway.zuul.utils;

import org.microser.gataway.zuul.system.entity.Role;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 匹配URI
 *
 * @author liujiamiao
 * @email 2544296058@qq.com
 * @date 2020-11-26 16:55
 */
public class MatchingURI {


    /**
     * 拆分权限
     * @param val
     * @return
     */
    public static String[] split(String val){
        if(val.indexOf("roles[")!=-1){
            StringBuilder sb = new StringBuilder();
            String[] split = split(val, "roles[", "]");
            return split;
        }else{
            return val.split(",");
        }
    }


    public static String[] split(String val,String begin,String end){
        int left = 0;
        int index = 0;
        List<String> strList = new ArrayList<>();
        for(int i = 0;i<val.length();i++){
            if(val.charAt(i)==','&&left==0){
                String substring = val.substring(index, i);
                if(StringUtils.isEmpty(substring.trim())||substring.trim().equals(",")){
                    index = i+1;
                    continue;
                }
                strList.add(substring.trim());
                index = i+1;
            } else if(val.charAt(i)=='|'&&left==0){
                if(i+1<val.length()&&val.charAt(i+1)=='|'){
                    strList.add(val.substring(index,i).trim()+"()");
                    index = i+2;
                    continue;
                }
            }
            else if(val.charAt(i)=='r'){
                int length = "roles[".length();
                if(i+length<val.length()){
                    if(val.substring(i,(i+length)).equals("roles[")){
                        left++;
                        i+=5;
                    }
                }
            }else if(val.charAt(i)==']'){
                left--;
            }
        }
        strList.add(val.substring(index).trim());
        String[] strs = new String[strList.size()];
        for(int i = 0;i<strList.size();i++){
            strs[i] = strList.get(i);
        }
        return strs;
    }
    /**
     * 匹配路由
     * @param key 配置的路由
     * @param uri 页面访问的路由
     * @return
     */
    public static boolean equlasUri(String key,String uri){
        int index = -1;

        Boolean flag = null;
        while(true){
            System.out.println("key = "+key+"; uri = "+uri);
            int index1 = key.indexOf("**");
            int index2 = key.indexOf("*");
            if(key.equals(uri)) {
                return true;
            }
            if(index1==-1&&index2!=-1){
                index = index2;
                flag = false;
            }else if(index1!=-1&&index2!=-1){
                if(index1<=index2){
                    index = index1;
                    flag = true;
                }else{
                    index = index2;
                    flag = false;
                }
            }else if(index1==-1&&index2==-1){
                break;
            }

            if (flag) {
                //**前面一大串是否相等
                if(uri.indexOf(key.substring(0,index))==0){
                    //**后面是否还有其他字符串要求
                    if(key.length()>index+2){
                        //截取**后面的字符串
                        key = key.substring(index + 2);//  /mapper*.add
                        String tempKey = key;
                        int temp = tempKey.indexOf("*");
                        if(temp!=-1){
                            tempKey = tempKey.substring(0, temp);//  /mapper
                        }

                        //uri 找key（*后面字符串 ）
                        int uriTemp = uri.indexOf(tempKey);
                        //**后面一串拼不上，说明不一致
                        if(uriTemp==-1){
                            return false;
                        }
                        //截取**后面匹配的字符串
                        uri = uri.substring(uriTemp);
                    }else{
                        //后面已经没有字符串了
                        return true;
                    }
                    //匹配 true
                }else{
                    return false;
                }
            } else {
                String beginKey = key.substring(0, index);
                String beginURI = uri.substring(0, index);
                //*前面字符串不相等
                if(!beginURI.equals(beginKey)){
                    return false;
                }
                int temp = -1;
                //截取* 后面字符串
                String lastKey = key.substring(index+1);
                String lastUri = uri.substring(index);

                // 条件 *后面没有条件，比如：*.png(有条件）
                if(StringUtils.isEmpty(lastKey)){
                    temp = lastUri.indexOf('/');
                    //要么没有/，如果有也是最后一个字符
                    if(temp==-1||temp==lastUri.length()-1){
                        return true;
                    }
                    return false;
                }else{
                    //*后面有条件，
                    
                    key = lastKey;
                    int keyTemp = lastKey.indexOf("*");
                    if(keyTemp!=-1){
                        lastKey = lastKey.substring(0,keyTemp);
                    }

                    temp = lastUri.indexOf(lastKey);
                    // *后面条件没有达到
                    if(temp==-1){
                        return false;
                    }

                    String center = lastUri.substring(0, temp);//user.png => user
                    if(center.indexOf('/')!=-1){
                        return false;
                    }

                    // 不相等说明后面还有  *匹配规则
                    if(!lastKey.equals(key)){
                        key = key.substring(keyTemp);
                        uri = lastUri.substring(temp+lastKey.length());
                    }else{
                        //后面没有*，条件又满足，结束匹配
                        return true;
                    }
                }
            }
        }
        return false;
    }


    /**
     * 是否包含该权限
     * @param permissionVal
     * @param permissionValue
     * @return
     */
    public static boolean includePermission(String permissionVal,List<String> permissionValue){
        String[] split = permissionVal.split("\\|\\|");
        for(String permission : split){
            if(permissionValue.contains(permission.trim())){
                //说明有该权限直接放行
                return true;
            }
        }
        return false;
    }

    /**
     * 是否包含该角色
     * @param permissionVal
     * @param roles
     * @return
     */
    public static boolean includeRole(String permissionVal,List<Role> roles){
        String[] split = permissionVal.split("\\|\\|");
        for(String permission : split){
            for(Role role : roles){
                if (role.getRoleName().equals(permission.trim())) {
                    return true;
                }
            }
        }
        return false;
    }


}
